from flask import Blueprint, jsonify, request, current_app
from applications.models import ProductCate
from applications.extensions import db
from datetime import datetime

# 创建商品分类蓝图
category_bp = Blueprint('category_bp', __name__, url_prefix='/system/goods-category')


@category_bp.route("/list", methods=['POST'])
def get_cate_list():
    """
    获取商品分类列表
    """
    try:
        # 获取所有顶级分类
        categories = ProductCate.query.filter_by(parent_id=None).order_by(ProductCate.sort_order.asc()).all()

        # 递归构建分类树
        def build_category_tree(category):
            children = category.children.order_by(ProductCate.sort_order.asc()).all()
            return {
                'id': category.id,
                'parent_id': category.parent_id,
                'name': category.name,
                'image': category.image,
                'sort_order': category.sort_order,
                'is_displayed': category.is_displayed,
                'children': [build_category_tree(child) for child in children] if children else []
            }

        # 构建分类树数据
        category_tree = [build_category_tree(category) for category in categories]

        return jsonify({'code': 200, 'message': '获取分类列表成功', 'data': category_tree})
    except Exception as e:
        current_app.logger.error(f'获取分类列表失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取分类列表失败: {str(e)}'}), 500


@category_bp.route("/tree", methods=['GET'])
def get_cate_tree():
    """
    获取商品分类树形结构
    """
    try:
        # 获取所有顶级分类
        categories = ProductCate.query.filter_by(parent_id=None).order_by(ProductCate.sort_order.asc()).all()

        # 递归构建分类树
        def build_category_tree(category):
            children = category.children.order_by(ProductCate.sort_order.asc()).all()
            return {
                'id': category.id,
                'label': category.name,
                'children': [build_category_tree(child) for child in children] if children else []
            }

        # 构建分类树数据
        category_tree = [build_category_tree(category) for category in categories]

        return jsonify({'code': 200, 'message': '获取分类树成功', 'data': category_tree})
    except Exception as e:
        current_app.logger.error(f'获取分类树失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取分类树失败: {str(e)}'}), 500


@category_bp.route("/detail", methods=['POST'])
def get_cate_detail():
    """
    获取商品分类详情
    """
    try:
        data = request.get_json()
        category_id = data.get('id')
        if not category_id:
            return jsonify({'code': 400, 'message': '缺少分类ID'}), 400

        category = ProductCate.query.get_or_404(category_id)

        # 构建分类详情数据
        category_data = {
            'id': category.id,
            'name': category.name,
            'image': category.image,
            'parent_id': category.parent_id,
            'sort_order': category.sort_order,
            'is_displayed': category.is_displayed,
            'create_time': category.create_time.strftime('%Y-%m-%d %H:%M:%S') if category.create_time else None,
            'update_time': category.update_time.strftime('%Y-%m-%d %H:%M:%S') if category.update_time else None
        }

        return jsonify({'code': 200, 'message': '获取分类详情成功', 'data': category_data})
    except Exception as e:
        current_app.logger.error(f'获取分类详情失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'获取分类详情失败: {str(e)}'}), 500


@category_bp.route("/add", methods=['POST'])
def add_cate():
    """
    添加商品分类
    """
    try:
        data = request.get_json()
        if not data:
            return jsonify({'code': 400, 'message': '请求数据不能为空'})

        required_fields = ['name']
        for field in required_fields:
            if field not in data:
                return jsonify({'code': 400, 'message': f'缺少必填字段: {field}'})
            if not data[field]:
                return jsonify({'code': 400, 'message': f'字段 {field} 不能为空'})

        # 如果 parent_id 为 0，则设置为 None，以符合外键约束
        parent_id = data.get('parent_id')
        parent_id = None if parent_id == 0 else parent_id
        
        new_category = ProductCate(
            name=data.get('name'),
            parent_id=parent_id,
            sort_order=data.get('sort_order', 0),
            is_displayed=data.get('is_displayed', True),
            image=data.get('image', ''),
            create_time=datetime.now(),
            update_time=datetime.now()
        )

        db.session.add(new_category)
        db.session.commit()

        return jsonify({'code': 201, 'message': '新增分类成功', 'data': {'id': new_category.id}}), 201

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'新增分类失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'新增分类失败: {str(e)}'})


@category_bp.route("/update", methods=['POST'])
def update_cate():
    """
    修改商品分类
    """
    try:
        data = request.get_json()
        category_id = data.get('id')
        if not category_id:
            return jsonify({'code': 400, 'message': '缺少分类ID'}), 400

        category = ProductCate.query.get_or_404(category_id)

        if 'name' in data:
            category.name = data['name']
        if 'parent_id' in data:
            # 如果 parent_id 为 0，则设置为 None，以符合外键约束
            category.parent_id = None if data['parent_id'] == 0 else data['parent_id']
        if 'sort_order' in data:
            category.sort_order = data['sort_order']
        if 'is_displayed' in data:
            category.is_displayed = data['is_displayed']
        if 'image' in data:
            category.image = data['image']
            
        # 更新修改时间
        category.update_time = datetime.now()

        db.session.commit()

        return jsonify({'code': 200, 'message': '分类信息修改成功'}), 200

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'修改分类信息失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'修改分类信息失败: {str(e)}'}), 500


@category_bp.route("/delete", methods=['POST'])
def del_cate():
    """
    删除商品分类
    """
    try:
        data = request.get_json()
        category_id = data.get('id')
        if not category_id:
            return jsonify({'code': 400, 'message': '缺少分类ID'}), 400

        category = ProductCate.query.get_or_404(category_id)

        db.session.delete(category)
        db.session.commit()

        return jsonify({'code': 200, 'message': '分类删除成功'}), 200

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'删除分类失败: {str(e)}')
        return jsonify({'code': 500, 'message': f'删除分类失败: {str(e)}'}), 500

def register_category_bps(app):
    app.register_blueprint(category_bp)